<?php

namespace MyLogger\Formatters;

use MyLogger\Logger;

class HtmlFormatter implements FormatterInterface
{
    protected $dateFormat;
    protected $levelStyles = [
        Logger::DEBUG => 'color: #666;',
        Logger::INFO => 'color: #2e86c1;',
        Logger::NOTICE => 'color: #27ae60;',
        Logger::WARNING => 'color: #f39c12;',
        Logger::ERROR => 'color: #c0392b;',
        Logger::CRITICAL => 'color: #8e44ad; font-weight: bold;',
        Logger::ALERT => 'color: #d35400; font-weight: bold;',
        Logger::EMERGENCY => 'color: #c0392b; font-weight: bold; background: #f2dede;',
    ];

    public function __construct(string $dateFormat = 'Y-m-d H:i:s')
    {
        $this->dateFormat = $dateFormat;
    }

    public function format(array $record): string
    {
        $style = $this->levelStyles[$record['level']] ?? '';
        $context = !empty($record['context']) 
            ? '<pre>' . htmlspecialchars(json_encode($record['context'], JSON_PRETTY_PRINT)) . '</pre>' 
            : '';
        
        return sprintf(
            '<div style="margin: 5px 0; padding: 5px; border-left: 3px solid; %s">' .
                '<span style="font-weight: bold;">[%s]</span> ' .
                '<span style="%s">%s</span>: ' .
                '%s' .
                '%s' .
            '</div>',
            $style,
            $record['datetime']->format($this->dateFormat),
            $style,
            $record['level_name'],
            nl2br(htmlspecialchars($record['message'])),
            $context
        );
    }
}